package com.ysu.concurrency.thread.lock.testLock;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author 郭辉
 * @className LockDemo
 * @description 可重入锁演示
 * @date 2022/1/12 15:23
 * @company 海康威视
 */
public class ReentrantLockDemo {
    /**
     * 当A拿到锁执行call方法时，执行call方法后，会自动拿到 message() 方法锁，这便是可重入锁
     * */
    public static void main(String[] args) {
        Phone phone = new Phone();

        new Thread(()->{
            phone.call();
        },"A").start();

        new Thread(()->{
            phone.call();
        },"B").start();
    }
}

/**
 * 基于 synchronized
 * */
class Phone{
    public synchronized void call(){
        System.out.println(Thread.currentThread().getName() + "call");
        message();
    }

    public synchronized void message(){
        System.out.println(Thread.currentThread().getName() + "message");
    }
}

/**
 * 基于 lock
 * */
class Phone2{
    Lock lock = new ReentrantLock();
    public void call(){
        lock.lock();
        try {
            System.out.println(Thread.currentThread().getName() + "call");
            message();
        } catch (Exception e){
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public void message(){
        lock.lock();
        try {
            System.out.println(Thread.currentThread().getName() + "message");
        } catch (Exception e){
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
}